import { useState, useRef } from 'react';
import type { CardType } from '../../types/requestType';

// 定义分类和课程数据接口
interface Category {
  id: number;
  name: string;
  type: string;
  subCategories: string[];
  courses: Course[];
}

interface Course {
  id: number;
  title: string;
  coverImg: string;
  price: number;
  level: string;
}

// 分类导航组件
const Classify = () => {
  // 模拟分类数据，包含子分类和课程信息
  const categories: Category[] = [
    { id: 1, name: '后端|架构', type: 'backend', subCategories: ['Java', 'Python', 'SpringBoot', '必备基础'], courses: [
      { id: 101, title: '零基础学AI大模型Spring...', coverImg: 'https://placehold.co/300x160/3498db/ffffff?text=AI+SpringBoot', price: 69, level: '中级' },
      { id: 102, title: '新一代AI智能云盘(后...)', coverImg: 'https://placehold.co/300x160/e74c3c/ffffff?text=AI+云盘', price: 5699, level: '中级' },
      { id: 103, title: '新版JavaSE-自学入门...', coverImg: 'https://placehold.co/300x160/2ecc71/ffffff?text=JavaSE', price: 29.8, level: '中级' }
    ]},
    { id: 2, name: '前端|全栈', type: 'frontend', subCategories: ['HTML/CSS', 'JavaScript', 'React', 'Vue', 'Angular'], courses: [
      { id: 201, title: 'Web前端开发从入门到精通', coverImg: 'https://placehold.co/300x160/9b59b6/ffffff?text=Web前端', price: 199, level: '初级' },
      { id: 202, title: 'React全家桶实战项目', coverImg: 'https://placehold.co/300x160/e67e22/ffffff?text=React', price: 299, level: '中级' },
      { id: 203, title: 'Vue3企业级应用开发', coverImg: 'https://placehold.co/300x160/1abc9c/ffffff?text=Vue3', price: 399, level: '高级' }
    ]},
    { id: 3, name: '测试|测开', type: 'testing', subCategories: ['功能测试', '自动化测试', '性能测试', '测试开发'], courses: [
      { id: 301, title: 'WebUI自动化测试 Selenium4+TestNG', coverImg: 'https://placehold.co/300x160/f1c40f/ffffff?text=自动化测试', price: 39, level: '中级' },
      { id: 302, title: '爬虫WebUI自动化测试...', coverImg: 'https://placehold.co/300x160/8e44ad/ffffff?text=爬虫测试', price: 49, level: '中级' }
    ]},
    { id: 4, name: '运维|容器', type: 'devops', subCategories: ['Linux', 'Docker', 'Kubernetes', 'CI/CD'], courses: [
      { id: 401, title: 'Docker容器化实战', coverImg: 'https://placehold.co/300x160/34495e/ffffff?text=Docker', price: 159, level: '中级' },
      { id: 402, title: 'K8s从入门到精通', coverImg: 'https://placehold.co/300x160/e74c3c/ffffff?text=K8s', price: 259, level: '高级' }
    ]},
    { id: 5, name: '架构|管理', type: 'architecture', subCategories: ['分布式', '微服务', '高并发', '项目管理'], courses: [
      { id: 501, title: '分布式系统设计与实现', coverImg: 'https://placehold.co/300x160/2c3e50/ffffff?text=分布式架构', price: 399, level: '高级' },
      { id: 502, title: '微服务架构实战', coverImg: 'https://placehold.co/300x160/16a085/ffffff?text=微服务', price: 499, level: '高级' }
    ]},
    { id: 6, name: '算法人工智能', type: 'ai', subCategories: ['机器学习', '深度学习', 'NLP', '计算机视觉'], courses: [
      { id: 601, title: '机器学习算法实战', coverImg: 'https://placehold.co/300x160/9b59b6/ffffff?text=机器学习', price: 599, level: '中级' },
      { id: 602, title: '深度学习入门到精通', coverImg: 'https://placehold.co/300x160/3498db/ffffff?text=深度学习', price: 699, level: '高级' }
    ]},
    { id: 7, name: '大数据', type: 'bigdata', subCategories: ['Hadoop', 'Spark', 'Flink', '数据仓库'], courses: [
      { id: 701, title: 'Hadoop大数据实战', coverImg: 'https://placehold.co/300x160/1abc9c/ffffff?text=Hadoop', price: 499, level: '中级' },
      { id: 702, title: 'Spark数据分析', coverImg: 'https://placehold.co/300x160/f39c12/ffffff?text=Spark', price: 599, level: '高级' }
    ]}
  ];

  // 当前选中的分类 - 初始值为null确保不展示任何内容
  const [selectedCategory, setSelectedCategory] = useState<Category | null>(null);
  // 当前选中的子分类
  const [selectedSubCategory, setSelectedSubCategory] = useState<string | null>(null);
  // 控制是否显示内容 - 初始值为false确保不展示内容
  const [showContent, setShowContent] = useState(false);
  
  // 引用分类导航区域
  const categoryRef = useRef<HTMLDivElement>(null);
  // 引用内容区域
  const contentRef = useRef<HTMLDivElement>(null);

  // 处理分类鼠标悬停事件
  const handleCategoryMouseEnter = (category: Category) => {
    setSelectedCategory(category);
    setSelectedSubCategory(null); // 重置子分类选中状态
    setShowContent(true); // 显示内容区域
  };

  // 处理分类鼠标移出事件
  const handleCategoryMouseLeave = () => {
    // 延迟隐藏，防止快速在分类间移动时频繁切换
    setTimeout(() => {
      if (categoryRef.current && contentRef.current) {
        // 检查鼠标是否在分类区域或内容区域内
        const isMouseInCategory = categoryRef.current.matches(':hover');
        const isMouseInContent = contentRef.current.matches(':hover');
        
        if (!isMouseInCategory && !isMouseInContent) {
          setShowContent(false);
          setSelectedCategory(null);
          setSelectedSubCategory(null);
        }
      }
    }, 100);
  };

  // 处理子分类点击事件
  const handleSubCategoryClick = (subCategory: string) => {
    setSelectedSubCategory(selectedSubCategory === subCategory ? null : subCategory);
  };

  // 处理内容区域鼠标移出事件
  const handleContentMouseLeave = () => {
    setShowContent(false);
    setSelectedCategory(null);
    setSelectedSubCategory(null);
  };

  // 根据选中的子分类过滤课程
  const filteredCourses = selectedSubCategory && selectedCategory
    ? selectedCategory.courses.filter(course => 
        course.title.includes(selectedSubCategory) || selectedSubCategory.includes(course.level)
      )
    : selectedCategory?.courses || [];

  return (
    <>
      {/* 左侧分类导航 - 保持固定位置 */}
      <div 
        ref={categoryRef}
        className="w-48 bg-white border-r border-gray-200 h-[400px] rounded-l shadow-[0_0_10px_0_#d7d7d7]"
        onMouseLeave={handleCategoryMouseLeave}
      >
        {categories.map((category) => (
          <div
            key={category.id}
            className={`
              px-4 py-3 cursor-pointer transition-all duration-200 ease-in-out
              flex items-center justify-between
              ${selectedCategory?.id === category.id 
                ? 'bg-gray-800 text-white' 
                : 'hover:bg-gray-100'}
            `}
            onMouseEnter={() => handleCategoryMouseEnter(category)}
            onClick={() => handleCategoryMouseEnter(category)}
          >
            <span className="text-sm font-medium">{category.name}</span>
            <span className="text-xs w-4 h-4 flex items-center justify-center">
              ▶
            </span>
          </div>
        ))}
      </div>
      
      {/* 右侧内容区域 - 使用绝对定位浮动在轮播图上方 */}
      {showContent && selectedCategory && (
        <div 
          ref={contentRef}
          className="absolute top-0 left-48 w-[600px] bg-white border-r border-gray-200 rounded-r shadow-[0_0_10px_0_#d7d7d7] z-10"
          onMouseLeave={handleContentMouseLeave}
        >
          <div className="p-6 h-[400px]">
            {/* 子分类标签区域 */}
            <div className="mb-6">
              <h3 className="text-lg font-bold mb-4">{selectedCategory.name.split('|')[1]}</h3>
              <div className="flex flex-wrap gap-2">
                {selectedCategory.subCategories.map((subCat) => (
                  <span
                    key={subCat}
                    className={`
                      px-3 py-1 rounded-full text-sm cursor-pointer transition-all
                      ${selectedSubCategory === subCat 
                        ? 'bg-blue-600 text-white' 
                        : 'bg-gray-200 text-gray-700 hover:bg-gray-300'}
                    `}
                    onClick={() => handleSubCategoryClick(subCat)}
                  >
                    {subCat}
                  </span>
                ))}
              </div>
            </div>
            
            {/* 课程列表区域 */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {filteredCourses.map((course) => (
                <div key={course.id} className="bg-white rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-shadow">
                  <div className="relative">
                    <img 
                      src={course.coverImg} 
                      alt={course.title} 
                      className="w-full h-40 object-cover"
                    />
                    <div className="absolute top-2 right-2 bg-red-500 text-white text-xs px-2 py-1 rounded">
                      {course.level}
                    </div>
                  </div>
                  <div className="p-4">
                    <h4 className="text-base font-medium mb-2 line-clamp-2">{course.title}</h4>
                    <div className="flex items-center justify-between">
                      <span className="text-red-500 font-bold">¥{course.price}</span>
                      <button className="px-3 py-1 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm rounded transition-colors">
                        立即购买
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default Classify;